<template>
  <div style="width: 100%;background: white">
    <n-input
      v-model:value="task.name"
      type="textarea"
      placeholder="输入卡片标题"
      :autosize="{
        minRows: 1,
      }"
    />

    <TinyFluentEditor v-model="task.desc" class="mt-10" :data-type="false" :data-upgrade="false" />

    <n-space style="align-items: center;" class="mt-10">
      <NButton
        style="display: flex; align-items: center;transition: transform 0.3s ease;"
        :style="{ transform: `translateX(${showAdvanced ? '15px' : '0'})` }"
        type="primary"
        secondary
        @click="toggleAdvanced"
      >
        高级选项
      </NButton>
      <!-- 优先级选择 -->

      <ul class="advanced-priority" style="margin-left: 25px">
        <li v-for="(item, index) in priorityItems" :key="index" @click="selectCheckbox(item)">
          <n-tooltip placement="bottom" trigger="hover">
            <template #trigger>
              <n-icon
                :size="30"
                :color="item.p_color"
                :class="item.selected ? 'icon-square' : 'icon-checkbox'"
              >
                <!-- 这里假设您有 checkbox 和 square 两个图标组件 -->
                <Checkbox v-if="item.selected" />
                <Square v-if="!item.selected" />
              </n-icon>
            </template>
            <span>{{ item.p_name }}</span>
          </n-tooltip>
        </li>
      </ul>

      <n-badge :value="badgeValue" :max="99" :offset="badgeOffset" style="margin-left: 20px">
        <i class="i-fe:clock" style="width: 28px;height: 28px;display: flex;align-items: center;" />
      </n-badge>
    </n-space>

    <transition name="slide">
      <div
        v-if="showAdvanced" class="task-add-advanced mt-10"
        style="padding-bottom: 15px;display: flex;flex-direction: column;"
      >
        <div style="display: flex;align-items: center;margin-top: 10px;">
          <span style="flex: none">计划时间：</span>
          <n-date-picker
            v-model:value="selectTime"
            style="flex: 1;"
            type="datetimerange"
            :shortcuts="rangeShortcuts"
            :on-update:formatted-value="onUpdateFormattedValue"
            :on-update:value="onUpdateValue"
            :format="dateformat"
          />
        </div>

        <div style="display: flex; width: 100%;margin-top: 15px; align-items: center;">
          <span style="flex: none">⠀负责人：</span>
          <n-select
            v-model:value="task.owner"
            multiple
            :options="projectUsers"
            :value="task.owner"
            :render-label="renderLabel"
            :render-tag="renderMultipleSelectTag"
          />
        </div>

        <div style="display: flex; width: 100%;margin-top: 15px; align-items: center;">
          <span style="flex: none">⠀协助人：</span>
          <n-select
            v-model:value="task.assist"
            multiple
            filterable
            :options="projectUsers"
            :render-label="renderLabel"
            :render-tag="renderMultipleSelectTag"
          />
        </div>
      </div>
    </transition>

    <n-space style="justify-content: right;align-items: center" class="mr-10 mt-15">
      <!--      <n-checkbox v-model:checked="addAgain"> -->
      <!--        提交继续添加 -->
      <!--      </n-checkbox> -->   <!-- 延后再考虑这个事情 -->
      <NButton @click="handleCancel">
        取消
      </NButton>
      <NButton type="primary" @click="addTask">
        添加卡片
      </NButton>
    </n-space>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store'
import TinyFluentEditor from '@opentiny/vue-fluent-editor'
import { Checkbox, Square } from '@vicons/ionicons5'
import { NAvatar, NButton, NTag, NText, type SelectRenderLabel, type SelectRenderTag } from 'naive-ui'
import { defineProps, h, ref, watch } from 'vue'

import api from './api'

const props = withDefaults(defineProps<{ columnInfo: object, project: object }>(), {
  columnInfo: () => ({}),
  project: () => ({}),
})

const emit = defineEmits(['closeModal'])

const userStore = useUserStore()

// 时间天数显示
const badgeValue = ref(1)

// 开始时间
function getStartTime(days) {
  const date = new Date()
  date.setHours(9, 0, 0, 0) // 设置为9点
  date.setDate(date.getDate() + days)
  return date.getTime()
}

// 结束时间
function getEndTime(days) {
  const date = new Date()
  date.setHours(18, 0, 0, 0) // 设置为18点
  date.setDate(date.getDate() + days)
  return date.getTime()
}

const selectTime = ref([new Date().getTime(), getEndTime(1)])

// 新建项目的实体
const task = ref({
  name: '',
  desc: '',
  projectId: '',
  content: '',
  owner: [],
  assist: [],
  times: '',
  pLevel: '',
  pName: '',
  pColor: '',
})

// 时间格式化显示
const dateformat = ref('yyyy-MM-dd HH:mm:ss')

function onUpdateFormattedValue(value) {
  task.value.times = value
  console.log(`onUpdateFormattedValue----->${task.value.times}`)
}

function onUpdateValue(value) {
  console.log(`onUpdateValue----->${value}`)
  const date1 = new Date(value[0])
  const date2 = new Date(value[1])
  // 计算两个日期之间的毫秒差
  const diffInMilliseconds = Math.abs(date2.getTime() - date1.getTime())
  console.log(`diffInMilliseconds-->${diffInMilliseconds}`)
  // 将毫秒差转换为天数
  const diffInDays = Math.ceil(diffInMilliseconds / (24 * 60 * 60 * 1000)) // 向上取整
  console.log(diffInDays)
  badgeValue.value = diffInDays
}

const badgeOffset = ref([-2, 2])

function handleCancel() {
  emit('closeModal', false)
}

// 优先级
const priorityItems = ref([
  { p_color: '#c91818', p_name: '重要且紧急', p_level: '1', selected: true, days: 1 },
  { p_color: '#e6c128', p_name: '重要不紧急', p_level: '2', selected: false, days: 3 },
  { p_color: '#0556ec', p_name: '不重要不紧急', p_level: '3', selected: false, days: 5 },
])

// 点击图标时调用
function selectCheckbox(item) {
  // 将所有项的 selected 设置为 false
  priorityItems.value.forEach(i => (i.selected = false))
  item.selected = true
  selectTime.value = [new Date().getTime(), getEndTime(item.days)]
  badgeValue.value = item.days // 修改标记
}

// 高级选项
const showAdvanced = ref(false)

function toggleAdvanced() {
  showAdvanced.value = !showAdvanced.value
}

// 头像列表
const projectUsers = ref([])

// 提交后继续添加
// const addAgain = ref(false)

// 快捷时间选择
const rangeShortcuts = ref({
  今天: [getStartTime(0), getEndTime(0)] as const,
  明天: [getStartTime(1), getEndTime(1)] as const,
  本周: [getStartTime(1 - new Date().getDay()), getEndTime(7 - new Date().getDay())] as const,
})

async function addTask() {
  const times = task.value.times
  console.log(`times-->${times}`)
  console.log(times)
  console.log(`点击了这里......${props.projectId}`)
  const selectedItem = priorityItems.value.find(item => item.selected)

  console.log(`点击了这里2......${selectedItem}`)
  console.log(`  selectedItem.p_color......${selectedItem.p_color}`)
  console.log(selectedItem)

  console.log(`项目id-->${props.project.id}`)

  const name = task.value.name.trim()

  console.log(`name-->${name}`)
  if (!name) {
    $message.info('卡片名称不能为空')
    return
  }
  const desc = task.value.desc.trim()
  console.log(`desc-->${desc}`)

  const owner = task.value.owner
  console.log(`owner-->${owner}`)
  console.log(owner)

  const assist = task.value.assist
  console.log(`assist-->${assist}`)
  console.log(assist)

  const { data } = await api.addTask(props.project.id, name, desc, owner, assist, props.columnInfo.id, times, selectedItem.p_level, selectedItem.p_name, encodeURIComponent(selectedItem.p_color))
  console.log(`添加任务返回-->${data}`)
  $message.success('添加卡片成功')
  emit('closeModal', true)
}

// watch(() => props.columnInfo, (newData) => {
//   // console.error(`columId 有变化>>>>${newData}`)
// }, { deep: true, immediate: true })

// 获取用户列表信息（职位和头像之类）
async function getProjectUserInfo(ids) {
  const { data } = await api.getBasic(ids.value)
  // console.log(`getProjectUserInfo data-->${data}`)
  // console.log(data)
  projectUsers.value = data
  projectUsers.value.forEach((item) => { // 增加value字段
    item.value = item.id
  })

  // 设置选中
  console.log(`userid is +${userStore.userId}`)

  // 找出列表中，属于当前用户的id，然后选中
  if (projectUsers.value.length > 0) {
    // 查找当前用户 ID 对应的用户，并设置为默认选中
    const currentUser = projectUsers.value.find(user => user.value === userStore.userId)
    if (currentUser) {
      // task.value.owner = currentUser.id;
      task.value.owner = [userStore.userId]
    }
  }
}

const ids = ref([])
watch(() => props.project, (newData) => {
  console.error(`project 有变化>>>>${newData}`)
  // if (newData && typeof newData === 'object' && Object.values(newData).length > 0) {
  // 请求http获取用户信息
  // const ids = Object.values(newData).map(item => item.id);

  if (newData && Array.isArray(newData.project_user)) {
    // 使用 map 方法提取每个元素的 id
    ids.value = newData.project_user.map(item => item.userid)
    // console.error(`ids is ${ids.value}`)
    getProjectUserInfo(ids)
  }
}, { deep: true, immediate: true })

const renderLabel: SelectRenderLabel = (option) => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center',
      },
    },
    [
      h(NAvatar, {
        size: 'small',
        style: {
          color: 'white',
          backgroundColor: '#0556ec',
        },
        round: true,
        size: 'small',
      }, {
        default: () => option.username.substr(0, 2).toUpperCase(), // 这里传递 "M" 作为默认插槽的内容
      }),
      h(
        'div',
        {
          style: {
            marginLeft: '12px',
            padding: '4px 0',
          },
        },
        [
          h('div', null, [option.name as string]),
          h(
            NText,
            { depth: 3, tag: 'div' },
            [option.username as string],
            // {
            // default: () => 'description',
            // },
          ),
        ],
      ),
    ],
  )
}

const renderMultipleSelectTag: SelectRenderTag = ({
  option,
  handleClose,
}) => {
  return h(
    NTag,
    {
      style: {
        padding: '0 6px 0 4px',
      },
      round: true,
      closable: true,
      onClose: (e) => {
        e.stopPropagation()
        handleClose()
      },
    },
    {
      default: () =>
        h(
          'div',
          {
            style: {
              display: 'flex',
              alignItems: 'center',
            },
          },
          [
            h(NAvatar, {
              round: true,
              size: 22,
              style: {
                marginRight: '4px',
                color: 'white',
                backgroundColor: '#0556ec',
              },
            }, {
              default: () => option.username.substr(0, 1).toUpperCase(), // 插槽内容
            }),
            option.name.substr(0, 2).toUpperCase() as string,
          ],
        ),
    },
  )
}
</script>

<style scoped>
.task-add-advanced {
  margin: -16px 0 0;
  padding: 46px 32px 6px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.advanced-priority {
  margin-left: 8px;
  display: flex;
  align-items: center;
  height: 34px;
  overflow-y: hidden;
  overflow-x: auto;
}

.advanced-priority > li {
  list-style: none;
  margin-left: 3px;
  display: flex;
}

/* 定义 slide 动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
}

.slide-enter,
.slide-leave-to {
  opacity: 0;
  transform: translateY(-15px);
}

.slide-enter-to,
.slide-leave {
  opacity: 1;
  transform: translateY(0);
}

.icon-checkbox /deep/ .icon-color {
  //color: var(--color); /* 根据实际需要调整 */
}

.icon-square /deep/ .icon-color {
  color: red; /* Square 图标的颜色 */
}
</style>
